package com.daxt.controller.api;


import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.result.*;
import com.daxt.mapper.accept.BusinessInfoMapper;
import com.daxt.mapper.accept.FormDataMapper;
import com.daxt.mapper.archives.*;
import com.daxt.mapper.sys.ArchivesTypeMapper;
import com.daxt.model.constant.BaseConstants;
import com.daxt.model.dic.*;
import com.daxt.model.service.accept.vo.BusinessInfo;
import com.daxt.model.service.accept.vo.FormData;
import com.daxt.model.service.archives.vo.*;
import com.daxt.model.xml.oa.AccessoryXml;
import com.daxt.model.xml.oa.ProcessXml;
import com.daxt.service.ArchivesService;
import com.daxt.service.MountService;
import com.daxt.service.UploadService;
import com.daxt.utils.BaseUtil;
import com.daxt.utils.XmlUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "外部接收")
@RestController
@RequestMapping("/receive")
public class ReceiveController {


    @Autowired
    private UploadService uploadService;
    @Autowired
    private ArchivesDocReceiveMapper archivesDocReceiveMapper;
    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private ArchivesTypeMapper archivesTypeMapper;
    @Autowired
    private MountService mountService;
    @Autowired
    private ArchivesDocFileMapper archivesDocFileMapper;
    @Autowired
    private ArchivesTestingFourMapper archivesTestingFourMapper;
    @Autowired
    private ArchivesTestingFourMetadataMapper archivesTestingFourMetadataMapper;
    @Autowired
    private ArchivesTestingFourRecordMapper archivesTestingFourRecordMapper;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private FormDataMapper formDataMapper;
    @Autowired
    private BusinessInfoMapper businessInfoMapper;

//    @RequestParam("file") MultipartFile file

    @ApiOperation(value = "OA档案数据接收解析（zip）", notes = "")
    @PostMapping(value = "/oa")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) return ResultUtil.error("附件为空");

        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);

        Result<String> upload = uploadService.localUpload("OA", "", file);
        if (StringUtils.isNotEmpty(upload.getData())) {
            File downFile = new File(ossDir + upload.getData());

            String get32uuid = IdWorker.get32UUID();
            //外部接收目录
//        String directory = "D:/a/zipPage/";
            String directory = "receive/" + get32uuid + "/";
//
            ZipUtil.unzip(downFile, new File(ossDir + directory), Charset.forName("GBK"));

            File baseInfoXml = new File(ossDir + directory + "基本信息.xml");
            File stepXml = new File(ossDir + directory + "办理流程.xml");

            ArchivesDocReceive entity = new ArchivesDocReceive();
            entity = (ArchivesDocReceive) XmlUtil.parseOaPage(baseInfoXml, entity);
            entity.setCreateTime(LocalDateTime.now());
//        BaseInfoXml xml = new BaseInfoXml();
//        xml = (BaseInfoXml) XmlUtil.parseOaPage(downFile,xml);
            ProcessXml processXml = new ProcessXml();
            processXml = (ProcessXml) XmlUtil.parseOaPage(stepXml, processXml);
            entity.setStep(processXml.getStep());

            if (null != entity) {


                //收集整编
                ArchivesDoc doc = new ArchivesDoc();
                doc.setArchivalYear(entity.getYear());
                doc.setSecret(entity.getSecret());
                doc.setTitle(entity.getTitle());
                doc.setItemNum(entity.getDocNum());
                doc.setPages(entity.getPages());
                doc.setState(DicDocState.external.getKey());
                doc.setIsDelete(BaseConstants.DELETE_NORMAL);
                doc.setFileType(DicDocFileType.DOC.getKey());
                doc.setDossierId(0l);
                doc.setExt01(entity.getRecordNum());
                doc.setCreateTime(entity.getCreateTime());
//                doc.setDocFrom(entity.getSource());
                doc.setDocFrom(DicDocFrom.FROM_2.getKey());
                archivesDocMapper.insert(doc);


                //原始解析保存
//                archivesDocReceiveMapper.delete(new QueryWrapper<ArchivesDocReceive>().eq("filingId",entity.getFilingId()));
                entity.setDocId(doc.getId());

                archivesDocReceiveMapper.insert(entity);


                //附件上传
                entity.getAccessory().forEach((AccessoryXml accessory) -> {
                    ArchivesDocFile archivesDocFile = new ArchivesDocFile();
                    archivesDocFile.setDocId(doc.getId());
                    archivesDocFile.setFileUrl(directory + "附件/" + accessory.getFileName() + "." + accessory.getFileFormat());
                    archivesDocFile.setItemNum(doc.getItemNum());
                    archivesDocFile.setExtName(accessory.getFileFormat());
                    archivesDocFile.setCreateTime(LocalDateTime.now());
                    accessory.setFileUrl(archivesDocFile.getFileUrl());

                    Result<String> mountFile = mountService.baseMountFile(archivesDocFile);
                });


                //四性检测
                Result r = archivesService.fourDetection(entity);


                return ResultUtil.success();


            }
        }

        return upload;
    }


//    @ApiOperation(value = "解析OA包", notes = "")
//    @GetMapping("/parse")
//    @Transactional(rollbackFor = Exception.class)
//    public Result<String> parse(@ApiParam("接收包url") @RequestParam(value = "url",required = true) String url){
//
////        File downFile = new File("C:\\Users\\Administrator\\Desktop\\222\\测试档案001.zip");
//        File downFile = new File(SystemConfig.ossDir + url);
//
//        String get32uuid = IdWorker.get32UUID();
//        //外部接收目录
////        String directory = "D:/a/zipPage/";
//        String directory =  SystemConfig.ossDir + "receive/" + get32uuid + "/";
////
//        ZipUtil.unzip(downFile, new File(directory), Charset.forName("GBK"));
//
//        File baseInfoXml = new File(directory + "基本信息.xml");
//
//        ArchivesDocReceive entity = new ArchivesDocReceive();
//        entity = (ArchivesDocReceive) XmlUtil.parseOaPage(baseInfoXml,entity);
////        BaseInfoXml xml = new BaseInfoXml();
////        xml = (BaseInfoXml) XmlUtil.parseOaPage(downFile,xml);
////        ProcessXml xml = new ProcessXml();
////        xml = (ProcessXml) XmlUtil.parseOaPage(downFile,xml);
//
//        if(null != entity){
//            archivesDocReceiveMapper.delete(new QueryWrapper<ArchivesDocReceive>().eq("filingId",entity.getFilingId()));
//            entity.setCreateTime(LocalDateTime.now());
//            archivesDocReceiveMapper.insert(entity);
//
//            //收集整编
//            ArchivesDoc doc = new ArchivesDoc();
//            doc.setArchivalYear(entity.getYear());
//            doc.setSecret(entity.getSecret());
//            doc.setTitle(entity.getTitle());
//            doc.setItemNum(entity.getDocNum());
//            doc.setPages(entity.getPages());
//            archivesDocMapper.insert(doc);
//
//
//            //附件上传
//            List<AccessoryXml> accessorys = entity.getAccessory();
//            accessorys.forEach((AccessoryXml accessory)->{
//                ArchivesDocFile archivesDocFile = new ArchivesDocFile();
//                archivesDocFile.setDocId(doc.getId());
//                archivesDocFile.setFileUrl(directory + accessory.getFileName() + "." + accessory.getFileFormat());
//                archivesDocFile.setItemNum(doc.getItemNum());
//                archivesDocFile.setExtName(accessory.getFileFormat());
//                archivesDocFile.setCreateTime(LocalDateTime.now());
//
//                Result<String> mountFile = mountService.mountFile(archivesDocFile);
//            });
//
//
//
//
//        }
//
////        ArchivesDoc entity = new ArchivesDoc();
////        entity.setState("0");
////        QueryWrapper<ArchivesDoc> updateWrapper = new QueryWrapper<ArchivesDoc>();
////        updateWrapper.eq("fondsId", fondsId);
////        updateWrapper.eq("typeNum", typeNum);
////        updateWrapper.in("id", ids);
////
////        return ResultUtil.result(archivesDocMapper.update(entity, updateWrapper));
//        return ResultUtil.success();
//
//    }


    @ApiOperation(value = "外部文件加入整编库", notes = "")
    @PostMapping("/addToArchivesDoc")
    public Result<String> addToArchivesDoc(@ApiParam("全宗ID") @RequestParam(value = "fondsId", required = true) String fondsId
            , @ApiParam("门类ID") @RequestParam(value = "typeId", required = true) String typeId
            , @ApiParam("卷dossier 件doc") @RequestParam(value = "fileType", required = true) String fileType
            , @ApiParam("分类Id") @RequestParam(value = "classId", required = true) String classId
            , @RequestBody List<String> ids) {


        ArchivesType at = null;
        if (StringUtils.isNotEmpty(typeId)) {
            at = archivesTypeMapper.selectById(Long.parseLong(typeId));
            if (null == at) return ResultUtil.error( "门类不正确");
        }

        Result str= archivesService.automationDossierItemNumNum(at,fileType,classId,fondsId,ids);
        if("1001".equals(str.getCode())){
            return str;
        }

        //根据卷id获取该卷下的件id
       if ("dossier".equals(fileType)){
            QueryWrapper<ArchivesDoc> selectWrapper = new QueryWrapper<ArchivesDoc>();
            selectWrapper.in("dossierId",ids);
            List<ArchivesDoc> ArchivesDocs= archivesDocMapper.selectList(selectWrapper);
            for (int i=0;i<ArchivesDocs.size();i++){
                ids.add(ArchivesDocs.get(i).getId().toString());
            }
        }

        QueryWrapper<ArchivesDoc> updateWrapper = new QueryWrapper<ArchivesDoc>();
        updateWrapper.in("id", ids);
        ArchivesDoc entity = new ArchivesDoc();
        entity.setFondsId(fondsId);
        if (null != at) {
            entity.setTypeId(at.getId());
            entity.setTypeNum(at.getTypeNum());
        }
        if (classId!=null && !"".equals(classId)){

            entity.setClassId(Long.parseLong(classId));
        }
        if("doc".equals(fileType)){
            entity.setDossierId(0l);
        }

        entity.setState(DicDocState.approval.getKey());


        archivesDocMapper.update(entity, updateWrapper);


        return ResultUtil.success();
    }


    @ApiOperation(value = "获取外部接收文件列表", notes = "")
    @GetMapping("/list")
    public Result<PageInfo<ArchivesDoc>> list(@ApiParam("") @RequestParam(value = "pageNum", required = true, defaultValue = "1") Integer pageNum,
                                              @ApiParam("") @RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize,
                                              @ApiParam("案件题名") @RequestParam(value = "title", required = false) String title,
                                              @ApiParam("") @RequestParam(value = "ext01" ,required = false) String ext01,
                                              @ApiParam("系统来源id") @RequestParam(value = "docFrom" ,required = false) String docFrom,
                                              @ApiParam("责任者单位") @RequestParam(value = "dutyCompany" ,required = false) String dutyCompany,
                                              @ApiParam("doc件 dossier卷") @RequestParam(value = "fileType" ,required =false) String fileType) {

        QueryWrapper<ArchivesDoc> queryWrapper = new QueryWrapper<ArchivesDoc>();
        queryWrapper.eq("state", DicDocState.external.getKey());
        queryWrapper.eq("isDelete", BaseConstants.DELETE_NORMAL);
        queryWrapper.eq("dossierId","0");
        queryWrapper.eq(StringUtils.isNotEmpty(docFrom),"docFrom",docFrom);
        queryWrapper.eq(StringUtils.isNotEmpty(dutyCompany),"dutyCompany",dutyCompany);
        queryWrapper.eq(StringUtils.isNotEmpty(fileType),"fileType", fileType);
        queryWrapper.like(StringUtils.isNotEmpty(title),"title",title);
        queryWrapper.like(StringUtils.isNotEmpty(ext01),"ext01",ext01);

        if("5".equals(docFrom)){
            queryWrapper.orderByDesc("createTime");
        }else{
            queryWrapper.orderByDesc("startTime");
        }



        //queryWrapper.orderByAsc("endTime");
        IPage<ArchivesDoc> page = new Page<ArchivesDoc>(pageNum, pageSize);
        IPage<ArchivesDoc> info = archivesDocMapper.selectPage(page, queryWrapper);

        //附件
        if (info.getRecords().size() > 0) {
            List<Long> docIds = new ArrayList<Long>();
            for (ArchivesDoc docE : info.getRecords()) {
                docIds.add(docE.getId());

                //四性检测结果
                QueryWrapper<ArchivesTestingFourRecord> qw = new QueryWrapper<ArchivesTestingFourRecord>();
                qw.eq("docId", docE.getId());
                qw.eq("source", docE.getDocFrom());
                List<ArchivesTestingFourRecord> atfrList = archivesTestingFourRecordMapper.selectList(qw);

                String fourTest = "false";
                if (BaseUtil.listIsNotNullElement(atfrList)) {

                    //按条件过滤
                    List<ArchivesTestingFourRecord> filterList = atfrList.stream().filter(bean -> bean.getTest().equals("false")).collect(Collectors.toList());
                    if (null == filterList || filterList.size() == 0) fourTest = "true";
                } else {
                    fourTest = "true";
                }
                docE.setFourTest(fourTest);

//                int i = archivesTestingFourRecordMapper.selectCount(qw);
//                if(i > 0){
//                    docE.setFourTest("false");
//                }else{
//                    docE.setFourTest("true");
//                }

            }
            QueryWrapper<ArchivesDocFile> queryWrapperFile = new QueryWrapper<ArchivesDocFile>();
            queryWrapperFile.in("docId", docIds);
            List<ArchivesDocFile> selectList = archivesDocFileMapper.selectList(queryWrapperFile);
            for (int i = 0; i < info.getRecords().size(); i++) {
                for (ArchivesDocFile archivesDocFile : selectList) {
                    if (archivesDocFile.getDocId() != null && archivesDocFile.getDocId().intValue() == info
                            .getRecords().get(i).getId().intValue()) {
                        info.getRecords().get(i).setIsFile("1");
                    }
                }
            }

        }


        PageInfo<ArchivesDoc> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());

        return ResultUtil.success(data);
    }

    @ApiOperation(value = "办结人信息", notes = "")
    @GetMapping("/fromdata")
    public Result<FormData> fromData(@ApiParam("档案ID") @RequestParam(value="docId") String docId) {
        QueryWrapper<FormData> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("docId",docId);
        FormData formData=formDataMapper.selectOne(queryWrapper);

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", formData);

    }

    @ApiOperation(value = "业务详细信息", notes = "")
    @GetMapping("/businessInfo")
    public Result<BusinessInfo> businessInfo(@ApiParam("档案ID") @RequestParam(value="docId") String docId) {
        QueryWrapper<BusinessInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("docId",docId);
        BusinessInfo info=businessInfoMapper.selectOne(queryWrapper);

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", info);

    }


    //public static void main(String[] args) {
//        ArchivesDocReceive adr = new ArchivesDocReceive();
//        adr.setTitle("2222222");
//        // 得到类对象
//        Class userCla = (Class) adr.getClass();
//        /* 得到类中的所有属性集合 */
//        Field fs = null;
//        try {
//            fs = userCla.getDeclaredField("title");
//            fs.setAccessible(true); // 设置些属性是可以访问的
//            Object val = new Object();
//                val = fs.get(adr);
//                System.out.println("val："+val);
//                // 得到此属性的值
//        } catch (NoSuchFieldException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }


//        String sss = "{\"1\": {\"16\": \"1\", \"18\": \"2\"}, \"2\": {\"18\": \"日期时间型\"}, \"3\": {\"16\": \"#、￥、%、！、~、|\"}, \"4\": {\"16\": \"2011,1234\"}}";
//        Map jsonObject = (Map) JSONObject.parse(sss);
//        Map m1 = (Map) jsonObject.get("1");
//        Map m2 = (Map) jsonObject.get("2");
//        Map m3 = (Map) jsonObject.get("3");
//        Map m4 = (Map) jsonObject.get("4");
////        JSONArray jarr = jsonObject.getJSONArray("1");
////        JSONObject j1 = jsonObject2.getJSONObject("1");
//
//
//        System.err.println("================m1============");
//        m1.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));
//        System.err.println("================m1==end==========");
//
//        System.err.println("================m2============");
//        m2.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));
//        System.err.println("================m2==end==========");

        //System.err.println("----:");
    //}


}
